package com.karry.util;

import com.karry.mapper.BlogMapper;
import com.karry.mapper.RecordMapper;
import com.karry.pojo.Blog;
import com.karry.pojo.SensitiveWord;
import com.karry.service.impl.RecordServiceImpl;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.util.ArrayList;
import java.util.TimerTask;

import javax.servlet.ServletContext;

/**
 * 定时器
 * @author sxl
 *
 */
public class DelFileTask extends TimerTask{

    private static boolean isRunning = false;

    private ServletContext context = null;

    private SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory();

    public DelFileTask() {
        super();
    }

    public DelFileTask(ServletContext context) {
        this.context = context;
    }
    @Override
    public void run() {

        if (!isRunning) {

            SqlSession sqlSession = sqlSessionFactory.openSession(true);

            context.log("开始执行指定任务");
            /**
             * 自己的业务代码
             */
            //System.out.println(System.currentTimeMillis());
            /**  获取全部公开博客  **/
            BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
            RecordMapper recordMapper =sqlSession.getMapper(RecordMapper.class);
            ArrayList<Blog> blogs = mapper.searchAllOpenBlog();
            /**  获取全部违规词  **/

            //统计总数
            int count = 0;

            ArrayList<SensitiveWord> sensitiveWords = mapper.searchAllWord();
            for (Blog blog : blogs) {
                for (SensitiveWord sensitiveWord : sensitiveWords) {
                    String word = sensitiveWord.getWord();
                    if (blog.getTitle().contains(word) || blog.getTypeName().contains(word) || blog.getContent().contains(word) || blog.getUserName().contains(word)){
                        //含有违禁词汇，将该博客设为私密
                        int i = mapper.updateBlogToPrivate(blog.getId());
                        count++;
                        break;
                    }
                }
            }
            //统计此次作业
            recordMapper.insertRecord("定期检查违禁词汇", -1, -1, "查询违规公开博客数量: " + count + " 条", "#");
            System.out.println("执行定时任务完毕");
            sqlSession.close();
            isRunning = false;
            context.log("指定任务执行结束");
        } else {
            context.log("上一次任务执行还未结束");
        }
    }



}
